const express = require("express");
const router = express.Router();
const { Attachment, User } = require("../../models");
const { NotFound } = require("http-errors");
const { success, failure } = require("../../utils/response");
const { client } = require("../../utils/aliyun");

/**
 * 查询附件列表
 */
router.get("/", async (req, res) => {
  try {
    // 分页条件
    const pageIndex = Number(Math.abs(req.pageIndex)) || 1;
    const pageSize = Number(Math.abs(req.pageSize)) || 10;
    const offset = (pageIndex - 1) * pageSize;
    // 查询条件 包含用户信息 id 用户姓名  头像 排序
    const condition = {
      include: [
        {
          modal: User,
          as: "user",
          attributes: ["id", "username", "avatar"],
        },
      ],
      order: [["id", "desc"]],
      limit: pageSize,
      offset,
    };

    const { count, rows } = await Attachment.findAndCountAll(condition);

    success(res, "查询成功！", {
      pagination: {
        pageIndex,
        pageSize,
        total: count,
      },
      attachments: rows,
    });
    // 返回结果
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除附件
 */
router.delete("/:id", async (req, res) => {
  try {
    const attachment = getAttachment(req);

    // 删除阿里云OSS中的文件
    await client.delete(attachment.fullpath);

    // 删除数据库中的附件记录
    await attachment.destroy();

    success(res, "删除附件成功");
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除到回收站
 * @param {*} req 
 * @returns 
 * 
 * 注意：因为要传递数组过来，这里 用DELETE请求就不合适了。Express默认不会解析DELETE请求中的body，所以我们更改为POST请求
 * 接受到用户传递的所有文章ID后，直接丢到where里，调用destroy方法删除掉即可。
 * 这里的ID，可以是单条记录值，也可以是数组。
 */

router.post("/delete",async(req,res)=>{
  try {
    const {id} = req.body;

    await Article.destroy({where:{id:id}})
    success(res,'已删除到回收站')
  } catch (error) {
    failure(res,error)
  }
})

/**
 * 恢复、多线批量恢复
 * @param {*} req 
 * @returns 
 */
router.post('/restore',async(req,res)=>{
  try {
    const {id} = req.body;

    await Article.restore({where:{id}})
    success(res,'已恢复成功。')
  } catch (error) {
    failure(res,error)
  }
})

/**
 * 彻底删除数据
 * @param {*} req 
 * @returns 
 */
router.post('/force_delete',async(req,res)=>{
  try {
    const {id} = req.body

    await Article.destroy({
      where:{id},
      // 强制删除
      force:true,
    })
    success(res,'已彻底删除')
  } catch (error) {
    failure(res,error)
  }
})

// 查询当前附件
async function getAttachment(req) {
  // 获取参数
  const { id } = req.params;

  // 查询附件id
  const attachment = await Attachment.findByPk(id);

  if (!attachment) {
    throw new NotFound("没有找到此附件！");
  }

  return attachment;
}


module.exports = router
